package com.juicygames.framework.gamepart;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.util.Log;

import com.juicygames.framework.GameAction;
import com.juicygames.framework.exception.GameActionNotHandled;

public class HandlersComponent {
	private final static String LOGTAG = HandlersComponent.class.getName();
	
	private GamePart componentParent;
	private Map<Class<? extends GameAction>, List<? extends GameHandler>> handlersMap;
	
	public HandlersComponent(GamePart gamePart) {
		
		this.componentParent = gamePart;
		
		handlersMap = new HashMap<Class<? extends GameAction>, List<? extends GameHandler>>();
	}
	
	public <HandlerTypeParam extends GameHandler> HandlerTypeParam addHandler(HandlerTypeParam handler) {
		
		componentParent.addPart(handler);
		
		Log.i(LOGTAG, "Adding GameHandler " + handler.toString() + " to " + componentParent.toString());
		
		if (!handlersMap.containsKey(handler.getActionClassHandled())) {
			
			List<HandlerTypeParam> handlerList = new ArrayList<HandlerTypeParam>();
			handlerList.add(handler);
			handlersMap.put(handler.getActionClassHandled(), handlerList);
			
		} else {
			
			List<HandlerTypeParam> handlerList = (List<HandlerTypeParam>)handlersMap.get(handler.getActionClassHandled());
			handlerList.add(handler);
			
		}
		return handler;
	}
	
	public void handleAction(GameAction action) throws GameActionNotHandled {
		
		if (!handlersMap.containsKey(action.getClass())) {
			throw new GameActionNotHandled(componentParent.toString() + " doesn't handle " + action.toString());
		}
		
		List<GameHandler> handlersCopy = new ArrayList<GameHandler>(handlersMap.get(action.getClass()));
		for (GameHandler handler : handlersCopy) {
			handler.handle(action);
		}
	}
	
	public boolean tryToHandleAction(GameAction action) {
		try {
			handleAction(action);
			return true;
		} catch (GameActionNotHandled e) {
			return false;
		}
	}

}
